package org.zizi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.zizi.action.ActionService;
import org.zizi.dao.BaseDao;
import org.zizi.manager.Manager;
import org.zizi.manager.Managers;
import org.zizi.manager.impl.ActionManager;
import org.zizi.manager.impl.DaoManager;
import org.zizi.util.Options;

public class Launcher
{
	private final static Logger log = Logger.getLogger(Launcher.class);
	
	private boolean started = false;
	
	@SuppressWarnings("unchecked")
	public synchronized void startup() throws Exception
	{
		if (started) return;
		
		try
		{
			log.info("启动系统...");
			
			//载入配置文件
			Options options = new Options();
			options.load(new File("conf/system.conf"));
			
			//得到项目设置
			String name = options.get("ProjectClass", String.class);
			Class<? extends Project> clazz = (Class<? extends Project>)Class.forName(name);
			
			Project project = clazz.newInstance();
			
			//add Managers
			List<Class<? extends Manager>> managers = new ArrayList<Class<? extends Manager>>();
			project.addManager(managers);
			
			for (Class<? extends Manager> m : managers) Managers.add(m);
			
			//添加Action配置
			List<Class<? extends ActionService>> services = new ArrayList<Class<? extends ActionService>>();
			project.addActionServices(services);
			
			ActionManager am = Managers.get(ActionManager.class);
			for (Class<? extends ActionService> s : services) am.register(s);
			
			//初始化Managers
			List<Class<? extends BaseDao>> daos = new ArrayList<Class<? extends BaseDao>>();
			project.addDaoImpls(daos);
			
			DaoManager dm = Managers.get(DaoManager.class);
			for (Class<? extends BaseDao> d : daos) dm.register(d);
			
			dm.initialize(options);
			try
			{
				dm.begin();
				
				Managers.initialize(options);
				
				project.initialize(options);
				
				dm.commit();
			}
			finally
			{
				dm.end();
			}
			
			log.info("系统启动成功.");
		}
		catch(Exception e)
		{
			log.fatal("系统启动失败：", e);
			throw e;
		}
		
		started = true;
	}
	
	public synchronized void shutdown()
	{
		if (!started) return;
		started = false;
		
		log.info("关闭系统...");
		
		DaoManager dm = Managers.get(DaoManager.class);
		try
		{
			dm.begin();
			
			Managers.destroy();
			
			dm.commit();
		}
		catch (Exception e) 
		{
			log.error("关闭系统错误：", e);
		}
		finally
		{
			dm.end();
		}
		
		log.info("关闭系统完毕.");
	}
}
